package cn.yuanqiao.archive.management.service.impl;

import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.management.domain.*;
import cn.yuanqiao.archive.management.mapper.*;
import cn.yuanqiao.archive.management.service.IYqZpgzService;
import cn.yuanqiao.archive.management.utils.PackUtil;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 组盘规则Service业务层处理
 *
 * @author sy
 * @date 2023-07-10
 */
@Service
public class YqZpgzServiceImpl implements IYqZpgzService
{
    @Autowired
    private YqZpgzMapper yqZpgzMapper;

    @Autowired
    private YqPggMapper yqPggMapper;

    @Autowired
    private YqZpjlMapper yqZpjlMapper;

    @Autowired
    private YqZpmxMapper yqZpmxMapper;

    @Autowired
    private YqZtMapper yqZtMapper;

    // 定义每个批次的大小
    private static int BATCH_SIZE = 65535;

    /**
     * 查询组盘规则
     *
     * @param zpgzId 组盘规则主键
     * @return 组盘规则
     */
    @Override
    public YqZpgz selectYqZpgzByZpgzId(Long zpgzId)
    {
        YqZpgz yqZpgz = new YqZpgz();
        yqZpgz.setZpgzId(zpgzId);
        return yqZpgzMapper.selectYqZpgzByZpgzId(yqZpgz);
    }

    @Override
    public YqZpgz selectYqZpgzByPggId(Long pggId) {
        YqZpgz yqZpgz = new YqZpgz();
        yqZpgz.setPggId(pggId);
        yqZpgz = yqZpgzMapper.selectYqZpgzByPggId(yqZpgz);
        return yqZpgz;
    }

    /**
     * 查询组盘规则列表
     *
     * @param yqZpgz 组盘规则
     * @return 组盘规则
     */
    @Override
    public List<YqZpgz> selectYqZpgzList(YqZpgz yqZpgz)
    {
        return yqZpgzMapper.selectYqZpgzList(yqZpgz);
    }

    /**
     * 新增组盘规则
     *
     * @param yqZpgz 组盘规则
     * @return 结果
     */
    @Override
    public String insertYqZpgz(YqZpgz yqZpgz)
    {
        StringBuilder successMsg = new StringBuilder();
        LoginUser user = SecurityUtils.getLoginUser();

        if(user == null){
            user = new LoginUser();
            user.setUserId(1L);
        }

        yqZpgz.setCreatorId(user.getUserId());
        yqZpgz.setCreateTime(DateUtils.getNowDate());
        if(yqZpgzMapper.insertYqZpgz(yqZpgz)<=0){
            successMsg.append("组盘规则添加失败！");
        }
        return successMsg.toString();
    }

    /**
     * 修改组盘规则
     *
     * @param yqZpgz 组盘规则
     * @return 结果
     */
    @Override
    public String updateYqZpgz(YqZpgz yqZpgz)
    {
        StringBuilder successMsg = new StringBuilder();

//        if (selectYqZpgzByZpgzId(yqZpgz.getZpgzId()).getIsUse()==1){
//            successMsg.append("该组盘规则已使用，无法进行修改！\n");
//        }else {
//            LoginUser user = SecurityUtils.getLoginUser();
//
//            if(user == null){
//                user = new LoginUser();
//                user.setUserId(1L);
//            }
//
//            yqZpgz.setLastupdater(user.getUserId());
//            yqZpgz.setLastupdateTime(DateUtils.getNowDate());
//            if(yqZpgzMapper.updateYqZpgz(yqZpgz)>0){
//                successMsg.append("修改成功！");
//            };
//        }

        LoginUser user = SecurityUtils.getLoginUser();

        if(user == null){
            user = new LoginUser();
            user.setUserId(1L);
        }

        yqZpgz.setLastupdater(user.getUserId());
        yqZpgz.setLastupdateTime(DateUtils.getNowDate());
        if(yqZpgzMapper.updateYqZpgz(yqZpgz)<=0){
            successMsg.append("组盘规则修改失败！");
        }
        return successMsg.toString();
    }

    /**
     * 批量删除组盘规则
     *
     * @param zpgzIds 需要删除的组盘规则主键
     * @return 结果
     */
    @Override
    public String deleteYqZpgzByZpgzIds(Long[] zpgzIds)
    {
        StringBuilder failMsg = new StringBuilder();
        int successNum = 0;
        int failNum = 0;
        YqZpgz yqZpgz = new YqZpgz();
        for (int i = 0; i < zpgzIds.length; i++) {
            yqZpgz = selectYqZpgzByZpgzId(zpgzIds[i]);
            if (yqZpgz.getIsUse()==1){
                failMsg.append("该组盘规则已使用，无法进行删除！\n");
                failNum++;
            }else {
                yqZpgzMapper.deleteYqZpgzByZpgzId(yqZpgz);
                successNum++;
            }
        }
        if (failNum==0){
            return "删除成功"+successNum+"条！";
        }else {
            return "删除成功"+successNum+"条，删除失败"+failNum+"条。\n失败原因："+failMsg;
        }
    }

    /**
     * 删除组盘规则信息
     *
     * @param zpgzId 组盘规则主键
     * @return 结果
     */
    @Override
    public int deleteYqZpgzByZpgzId(Long zpgzId)
    {
        YqZpgz yqZpgz = new YqZpgz();
        yqZpgz.setZpgzId(zpgzId);
        return yqZpgzMapper.deleteYqZpgzByZpgzId(yqZpgz);
    }

    /**
     * 根据组盘规则进行组盘
     *
     * @param yqZpgz 组盘规则
     * @return 结果
     */
    @Override
    public List<Map<YqZpjl,List<YqZpmx>>> plan(HttpServletRequest request, YqZpgz yqZpgz){
        String errorMsg = "";
        if (null!=yqZpgz.getState()&&0==yqZpgz.getState()){
            if (null==yqZpgz.getZpgzId()&&yqZpgzMapper.selectYqZpgzNumByPggId(yqZpgz)<1){
                yqZpgz.setZpgzId(SnowflakeIdGenerator.generateId());
                errorMsg = insertYqZpgz(yqZpgz);
            }else {
                errorMsg = updateYqZpgz(yqZpgz);
            }
        }
        if (StringUtils.isNotEmpty(errorMsg)){
            List<Map<YqZpjl, List<YqZpmx>>> errorMsgList = new LinkedList<>();
            Map<YqZpjl, List<YqZpmx>> errorMsgMap = new HashMap<>();
            YqZpjl yqZpjl = new YqZpjl();
            yqZpjl.setErrorMsg(errorMsg);
            errorMsgMap.put(yqZpjl, null);
            errorMsgList.add(errorMsgMap);
            return errorMsgList;
        }
        List<Map<YqZpjl,List<YqZpmx>>> plan = new LinkedList<>();
        Map<YqZpjl,List<YqZpmx>> z = new HashMap<>();
        List<YqZpmx> yqZpmxList = new LinkedList<>();
        Long zpgzId = yqZpgz.getZpgzId();
        Long pggId = yqZpgz.getPggId();
        Long categoryId = yqZpgz.getCategoryId();
        YqPgg yqPgg = new YqPgg();
        yqPgg.setPggId(pggId);
        yqPgg = yqPggMapper.selectYqPggByPggId(yqPgg);
        String pggName = yqPgg.getPggName();
        Double pggSize = Double.valueOf(yqPgg.getSize());
        Double resSizeLong = Double.valueOf(yqPgg.getSize());
        String categoryName = yqZpgz.getCategoryName();
        String DA_TABLE = "";
        String EFILE_TABLE_NAME = "";
//        String userCode = SecurityUtils.getTenantCode();
        String userCode = SecurityUtils.getTenantCode();
        String categoryTable = userCode + "_CATEGORY";
        String FOLDER = userCode + "_YQDA_FOLDER";
        List<Map<String,String>> categoryMap=yqZpgzMapper.selectCategory(categoryTable,categoryId);
        //根据整理方式选择分表
//        if (String.valueOf(categoryMap.get(0).get("TYPE")).equals("0")){
//            DA_TABLE = categoryMap.get(0).get("FILE_TABLE_NAME");
//        }else if (String.valueOf(categoryMap.get(0).get("TYPE")).equals("1")){
//            DA_TABLE = categoryMap.get(0).get("FOLDER_TABLE_NAME");
//        }else {
//            DA_TABLE = categoryMap.get(0).get("ITEM_TABLE_NAME");
//        }
        if (String.valueOf(categoryMap.get(0).get("TYPE")).equals("0")){
            DA_TABLE = categoryMap.get(0).get("FILE_TABLE_NAME");
        }else {
            DA_TABLE = categoryMap.get(0).get("FOLDER_TABLE_NAME");
        }

        EFILE_TABLE_NAME = categoryMap.get(0).get("EFILE_TABLE_NAME");

        if (StringUtils.isNotEmpty(yqZpgz.getStartTime())){
            yqZpgz.setStartTime(yqZpgz.getStartTime().replaceAll("-",""));
        }else {
            yqZpgz.setStartTime("19700101");
        }
        if (StringUtils.isNotEmpty(yqZpgz.getEndTime())){
            yqZpgz.setEndTime(yqZpgz.getEndTime().replaceAll("-",""));
        }else {
            Date date = new Date();
            date.setTime(Long.MAX_VALUE);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String rq = sdf.format(date);
            yqZpgz.setEndTime(rq);
        }
        List<Map<String,String>> daList=yqZpgzMapper.selectDa(DA_TABLE,yqZpgz.getStartTime(),yqZpgz.getEndTime(),yqZpgz.getBgqx(),yqZpgz.getMj());
        if (daList.size()==0){
            List<Map<YqZpjl, List<YqZpmx>>> errorMsgList = new LinkedList<>();
            Map<YqZpjl, List<YqZpmx>> errorMsgMap = new HashMap<>();
            YqZpjl yqZpjl = new YqZpjl();
            yqZpjl.setErrorMsg("未查询到符合规则的档案！");
            errorMsgMap.put(yqZpjl, null);
            errorMsgList.add(errorMsgMap);
            return errorMsgList;
        }
        Long[] idArray = new Long[daList.size()];
        for (int i = 0; i < daList.size(); i++) {
            Map<String, String> map = daList.get(i);
            String idStr = String.valueOf(map.get("ID"));
            Long id = Long.valueOf(idStr);
            idArray[i] = id;
        }
        //项目或卷（暂时项目按卷类型处理）
        if (!String.valueOf(categoryMap.get(0).get("TYPE")).equals("0")){
//            if (String.valueOf(categoryMap.get(0).get("TYPE")).equals("1")){
//                //卷
//                daList = yqZpgzMapper.selectFolder(FOLDER,DA_TABLE,idArray);
//            }else {
//                //项目
//                daList = yqZpgzMapper.selectFolderXm(FOLDER,DA_TABLE,idArray);
//            }
            daList = yqZpgzMapper.selectFolder(FOLDER,DA_TABLE,idArray);
            if (daList.size()!=0){
                idArray = new Long[daList.size()];
                for (int i = 0; i < daList.size(); i++) {
                    Map<String, String> map = daList.get(i);
                    String idStr = String.valueOf(map.get("ID"));
                    Long id = Long.valueOf(idStr);
                    idArray[i] = id;
                }
            }else {
                List<Map<YqZpjl, List<YqZpmx>>> errorMsgList = new LinkedList<>();
                Map<YqZpjl, List<YqZpmx>> errorMsgMap = new HashMap<>();
                YqZpjl yqZpjl = new YqZpjl();
                yqZpjl.setErrorMsg("未查询到电子文件！");
                errorMsgMap.put(yqZpjl, null);
                errorMsgList.add(errorMsgMap);
                return errorMsgList;
            }
        }

        //获取电子文件信息列表
        List<Map<String,String>> efileList = new ArrayList<>();
        if (!String.valueOf(categoryMap.get(0).get("TYPE")).equals("0")){
            if (daList.size()!=0){
//                efileList = yqZpgzMapper.selectEfileByJuan(FOLDER,EFILE_TABLE_NAME,idArray,idArray);
                for (int i = 0; i < idArray.length; i += BATCH_SIZE) {
                    int end = Math.min(i + BATCH_SIZE, idArray.length);
                    List<Map<String, String>> batchResult = yqZpgzMapper.selectEfileByJuan(FOLDER, EFILE_TABLE_NAME, Arrays.copyOfRange(idArray, i, end), Arrays.copyOfRange(idArray, i, end));
                    efileList.addAll(batchResult);
                }
            }else {
//                for (int i = 0; i < idArray.length; i++){
//                    Map<String,String> map = new HashMap<>();
//                    map.put("DOC_ID","");
//                    map.put("PATH","-");
//                    map.put("DA_ID",String.valueOf(idArray[i]));
//                    map.put("CON_TABLE_ID", String.valueOf(idArray[i]));
//                    map.put("DOC_FILE_SIZE","0");
//                    map.put("DOC_MNT","-");
//                    efileList.add(map);
//                }
                List<Map<YqZpjl, List<YqZpmx>>> errorMsgList = new LinkedList<>();
                Map<YqZpjl, List<YqZpmx>> errorMsgMap = new HashMap<>();
                YqZpjl yqZpjl = new YqZpjl();
                yqZpjl.setErrorMsg("未查询到电子文件！");
                errorMsgMap.put(yqZpjl, null);
                errorMsgList.add(errorMsgMap);
                return errorMsgList;
            }
        }else {
//            efileList=yqZpgzMapper.selectEfile(EFILE_TABLE_NAME,idArray);
            for (int i = 0; i < idArray.length; i += BATCH_SIZE) {
                int end = Math.min(i + BATCH_SIZE, idArray.length);
                List<Map<String, String>> batchResult = yqZpgzMapper.selectEfile( EFILE_TABLE_NAME, Arrays.copyOfRange(idArray, i, end));
                efileList.addAll(batchResult);
            }
        }
        if (efileList.size()==0){
            List<Map<YqZpjl, List<YqZpmx>>> errorMsgList = new LinkedList<>();
            Map<YqZpjl, List<YqZpmx>> errorMsgMap = new HashMap<>();
            YqZpjl yqZpjl = new YqZpjl();
            yqZpjl.setErrorMsg("未查询到电子文件！");
            errorMsgMap.put(yqZpjl, null);
            errorMsgList.add(errorMsgMap);
            return errorMsgList;
        }
        //把DH放入电子文件信息列表
        for (Map<String, String> daMap : daList) {
            String id = String.valueOf(daMap.get("ID"));
            String dh = String.valueOf(daMap.get("DH"));
            for (Map<String, String> efileMapObj : efileList) {
                String conTableId = String.valueOf(efileMapObj.get("CON_TABLE_ID"));
                if (id.equals(conTableId)) {
                    efileMapObj.put("DH", dh);
                }
            }
        }
        //根据DH来分组
        Map<String, List<Map<String, String>>> groupedMap = new HashMap<>();
        for (Map<String, String> efileMapObj : efileList) {
            String conTableId = efileMapObj.get("DH");
            List<Map<String, String>> groupList = groupedMap.getOrDefault(conTableId, new ArrayList<>());
            groupList.add(efileMapObj);
            groupedMap.put(conTableId, groupList);
        }

//        int i = 0;
        //在数据库中查询之前的最大盘号，之后增量
        int ph = 0;
        YqZpjl getPh = new YqZpjl();
        getPh.setPggId(pggId);
        getPh.setZpgzId(zpgzId);
        String result = yqZpjlMapper.selectPhByPggId(getPh);
        ph = result != null && !result.isEmpty() ? Integer.parseInt(result)+1 : 0;
        int zts = 0;
        Double zl = 0.0;
        Double fileSize = 0.0;
        boolean sign = false;
        for (int i = 0; i < groupedMap.size(); i++) {
            Map.Entry<String, List<Map<String, String>>> entry = groupedMap.entrySet().toArray(new Map.Entry[0])[i];
//        for (Map.Entry<String, List<Map<String, String>>> entry : groupedMap.entrySet()) {
            String conTableId = entry.getKey();
            List<Map<String, String>> groupList = entry.getValue();
            System.out.println("DH: " + conTableId);
            String PATH = "";
            String DOC_MNT = "";
            String daId = "";
//            i++;
//            Iterator<Map<String, String>> iterator = groupList.iterator();
            for (int j = 0; j < groupList.size(); j++) {
                Map<String, String> map = groupList.get(j);
//            if (iterator.hasNext()) {
//                Map<String, String> map = iterator.next();
//            for (Map<String, String> map : groupList) {
//                i++;
                YqZpjl yqZpjl = new YqZpjl();
                yqZpjl.setZpjlId(SnowflakeIdGenerator.generateId());
                fileSize = Double.parseDouble(map.get("DOC_FILE_SIZE"))  * 1.2 ;
                PATH = String.valueOf(map.get("PATH"));
                DOC_MNT = String.valueOf(map.get("DOC_MNT"));
                daId = String.valueOf(map.get("DA_ID"));
                if ((fileSize/ (1024 * 1024))>pggSize){
                    errorMsg += "档案"+conTableId+"的大小超过盘本身规格；";
                }else {
                    resSizeLong = resSizeLong - (fileSize/ (1024 * 1024));
                    zts++;
                    zl+=fileSize;
                    System.out.println(convertToReadableSize(zl));

//                    yqZpjl.setPh(String.valueOf(ph));
//                    //格式转换前的总量，字节数
//                    yqZpjl.setZl(zl.toString());
//                    //格式转换后的总量
//                    yqZpjl.setZlConvert(convertToReadableSize(zl));
//                    yqZpjl.setZts(String.valueOf(zts));
//                    yqZpjl.setZpgzId(zpgzId);
//                    yqZpjl.setPggId(pggId);
//                    yqZpjl.setPggName(pggName);

                    YqZpmx yqZpmx = new YqZpmx();
                    yqZpmx.setZpjlId(yqZpjl.getZpjlId());
                    yqZpmx.setDaId(Long.valueOf(daId));
                    yqZpmx.setCategoryName(categoryName);
                    yqZpmx.setDh(conTableId);
                    yqZpmx.setPath(PATH);
                    yqZpmx.setDocMnt(DOC_MNT);
//                    fileSize = fileSize/ (1024 * 1024);
                    yqZpmx.setDocFileSize(String.valueOf(fileSize));
                    yqZpmx.setDocFileSizeConvert(convertToReadableSize(fileSize));
                    yqZpmx.setCategoryId(categoryId);
                    yqZpmx.setSubTableName(EFILE_TABLE_NAME);

                    if(i < groupedMap.size()-1){
                        if (j < groupList.size()-1) {
                            Map<String, String> nextMap = groupList.get(j + 1);
                            Double nextfileSize = Double.parseDouble(nextMap.get("DOC_FILE_SIZE"))  * 1.2 ;
//                            if (((zl+nextfileSize)/ (1024 * 1024))>=pggSize){
//                                sign = true;
//                            }else {
//                                sign = false;
//                            }
//                            System.out.println(resSizeLong);
                            if (resSizeLong - (nextfileSize/ (1024.0 * 1024.0))<=0.0){
//                                System.out.println(00000000000000);
                                sign = true;
                            }else {
                                sign = false;
                            }
                        }else {
                            entry = groupedMap.entrySet().toArray(new Map.Entry[0])[i+1];
                            List<Map<String, String>> nextGroupList = entry.getValue();
                            Double nextfileSize = Double.parseDouble(nextGroupList.get(0).get("DOC_FILE_SIZE"))  * 1.2 ;
//                            if (((zl+nextfileSize)/ (1024 * 1024))>=pggSize){
//                                sign = true;
//                            }else {
//                                sign = false;
//                            }
                            if (resSizeLong - (nextfileSize/ (1024.0 * 1024.0))<=0.0){
//                                System.out.println(00000000000000);
                                sign = true;
                            }else {
                                sign = false;
                            }
                        }
                    }else {
                        if (j==groupList.size()-1){
                            sign = true;
                        }
                    }
//                    if (j + 1 < groupList.size()) {
//                        Map<String, String> nextMap = groupList.get(j + 1);
//                        Double nextfileSize = Double.parseDouble(nextMap.get("DOC_FILE_SIZE"))  * 1.2 ;
//                        if (((zl+nextfileSize)/ (1024 * 1024))>=pggSize){
//                            sign = true;
//                        }
//                    }else if (i <= groupedMap.size()-1){
//                        entry = groupedMap.entrySet().toArray(new Map.Entry[0])[i];
//                        List<Map<String, String>> nextGroupList = entry.getValue();
//                        Double nextfileSize = Double.parseDouble(nextGroupList.get(0).get("DOC_FILE_SIZE"))  * 1.2 ;
//                        if (((zl+nextfileSize)/ (1024 * 1024))>=pggSize){
//                            sign = true;
//                        }
//                    }

//                    if (iterator.hasNext()) {
//                        Map<String, String> nextMap = iterator.next();
//                        Double nextfileSize = Double.parseDouble(nextMap.get("DOC_FILE_SIZE"))  * 1.2 ;
//                        if (((zl+nextfileSize)/ (1024 * 1024))>=pggSize){
//                            sign = true;
//                        }else {
//                            sign = false;
//                        }
//                    }else {
//                        sign = true;
//                    }
                    if (sign){
                        ph++;
                        resSizeLong = pggSize;

                        yqZpjl.setPh(String.valueOf(ph));
                        yqZpjl.setZl(zl.toString());
                        yqZpjl.setZlConvert(convertToReadableSize(zl));
                        yqZpjl.setZts(String.valueOf(zts));
                        yqZpjl.setZpgzId(zpgzId);
                        yqZpjl.setPggId(pggId);
                        yqZpjl.setPggName(pggName);
                        yqZpmxList.add(yqZpmx);
                        z.put(yqZpjl,yqZpmxList);
                        plan.add(z);
                        zts = 0;
                        zl = 0.0;
                        fileSize = 0.0;
                        z = new HashMap<>();
                        yqZpmxList = new LinkedList<>();
//                        yqZpmxList.add(yqZpmx);
                        sign = false;
//                    }else if (resSizeLong <= 2.0 ){
//                        errorMsg += "剩余盘空间不足；";
//                        break;
                    }else {
                        yqZpmxList.add(yqZpmx);
                    }
                }

            }

            fileSize = fileSize*1.2;


        }

        if (StringUtils.isNotEmpty(errorMsg)) {
            List<Map<YqZpjl, List<YqZpmx>>> errorMsgList = new LinkedList<>();
            Map<YqZpjl, List<YqZpmx>> errorMsgMap = new HashMap<>();
            YqZpjl yqZpjl = new YqZpjl();
            yqZpjl.setErrorMsg(errorMsg);
            errorMsgMap.put(yqZpjl, null);
            errorMsgList.add(errorMsgMap);
            return errorMsgList;
        }
        HttpSession session = request.getSession();
        session.setAttribute("plan", plan);

        return plan;
    }

    /**
     * 新增组盘记录
     *
     * @param pggId 盘规格ID
     * @return 结果
     */
    @Override
    public String insertYqZpjl(HttpServletRequest request, Long pggId){
        HttpSession session = request.getSession();
        List<Map<YqZpjl,List<YqZpmx>>> zpjlList = new LinkedList<>();
        StringBuilder successMsg = new StringBuilder();

        if (session.getAttribute("plan") != null ){
            zpjlList = (List<Map<YqZpjl,List<YqZpmx>>>) session.getAttribute("plan");
        }else {
            YqZpgz yqZpgz = selectYqZpgzByPggId(pggId);
            zpjlList = plan(request,yqZpgz);
        }
        Long[] zpjlIds = new Long[zpjlList.size()];
        int index = 0;
        for (Map<YqZpjl, List<YqZpmx>> map : zpjlList) {
            for (Map.Entry<YqZpjl, List<YqZpmx>> entry : map.entrySet()) {
                YqZpjl yqZpjl = entry.getKey();
                zpjlIds[index] = yqZpjl.getZpjlId();
                index++;
                List<YqZpmx> yqZpmxList = entry.getValue();
//                Long zpjlId =  SnowflakeIdGenerator.generateId();
//                yqZpjl.setZpjlId(zpjlId);
//                yqZpjl.setZpjlId(SnowflakeIdGenerator.generateId());
                if(yqZpjlMapper.insertYqZpjl(yqZpjl)<=0){
                    successMsg.append("盘号为“"+yqZpjl.getPh()+"”的组盘记录添加失败！");
                    break;
                };
                for (YqZpmx yqZpmx : yqZpmxList) {
                    yqZpmx.setZpjlId(yqZpjl.getZpjlId());
                    if (yqZpjlMapper.insertYqZpmx(yqZpmx)<=0){
                        successMsg.append("档号为“"+yqZpmx.getDh()+"”的档案添加记录失败！");
                        break;
                    };
                }
            }
        }

        session.setAttribute("zpjlIds", zpjlIds);
        return successMsg.toString();

    }

    /**
     * 组盘下载
     *
     * @param zpjlId 组盘记录ID
     * @return 结果
     */
    @Override
    public String zupan(HttpServletResponse response, Long zpjlId, Long ztId) throws IOException {
        StringBuilder successMsg = new StringBuilder();
        YqZpjl yqZpjl = new YqZpjl();
        yqZpjl.setZpjlId(zpjlId);
        yqZpjl = yqZpjlMapper.selectYqZpjlByZpjlId(yqZpjl);
        String pggName = yqZpjl.getPggName();
        String ph = yqZpjl.getPh();
        YqZt yqZt = new YqZt();
        yqZt.setZtId(ztId);
        String place = "";
        String userCode = SecurityUtils.getTenantCode();
        String yqzpmxTable = "";
        String sourceFolderPath = "";
//        StringBuilder ids = new StringBuilder();
//        Long categoryId;
        String path = "";
        String packagePath="";
        PackUtil packUtil = new PackUtil();
        if (ztId!=-1L){
            place = yqZtMapper.selectYqZtByZtId(yqZt).getSavePath();
            String driveLetter = place.charAt(0)+":";
            File drive = new File(place);
            if (!drive.exists()) {
                successMsg.append("实物载体未连接到此电脑！");
                return successMsg.toString();
            }
        }
        YqXzjl yqXzjl = new YqXzjl();
        yqXzjl.setZtId(ztId);
        yqXzjl.setZpjlId(zpjlId);
        //查询下载记录
        if (yqZpjlMapper.selectYqXzjlNumber(yqXzjl)>0){
            successMsg.append("同一载体中，同一个信息包只能下载一次！");
            return successMsg.toString();
        }
        // 创建 pggName_ph 文件夹
//        String parentDirectory = pggName + "\\" + pggName + "_" + ph;
        String parentDirectory =  pggName + "_" + ph;
        File parentDir = new File(parentDirectory);
        parentDir.mkdir();
        if(StringUtils.isEmpty(userCode)){
            yqzpmxTable = "YQZPMX";
        }else {
                yqzpmxTable = userCode.toUpperCase()+"_YQZPMX";
//            yqzpmxTable = "YQZPMX";
        }
        List<YqZpmx> yqZpmxList =  yqZpjlMapper.selectYqZpmxList(yqzpmxTable,yqZpjl.getZpjlId());
        for(YqZpmx yqZpmx:yqZpmxList){
//            packagePath = yqZpmx.getDocMnt();
            packagePath = SpringUtils.getBean(ITenantSysConfigService.class).selectConfigByKey("YQ_MNT_PACKAGE");
            path = yqZpmx.getPath();
            path = path.substring(0, path.lastIndexOf("\\"));
//            sourceFolderPath  = packagePath+pggName;
            sourceFolderPath  = packagePath+pggName + "_" + ph;
            String nestedPath = packagePath+parentDirectory + File.separator + path;
            File folder = new File(nestedPath);
            try {
                if (!folder.exists()) {
                    if (folder.mkdirs()) {
                        System.out.println("文件夹创建成功");
                        String packPath = packUtil.getPersistenPackage(yqZpmx.getDaId().toString(), yqZpmx.getCategoryId(), nestedPath);
//                        File pack = new File(packPath);
//                        packUtil.copyZipFileToFolder(pack.getPath(),folder.getPath());
                    } else {
                        System.out.println("文件夹创建失败");
                    }
                } else {
                    System.out.println("文件夹已经存在");
                    String packPath = packUtil.getPersistenPackage(yqZpmx.getDaId().toString(), yqZpmx.getCategoryId(), nestedPath);
//                    File pack = new File(packPath);
//                    packUtil.copyZipFileToFolder(pack.getPath(),folder.getPath());
                }
            } catch (IOException e) {
                e.printStackTrace();
                successMsg.append("压缩文件失败！");
                return successMsg.toString();
            }catch (ServiceException e){
                e.printStackTrace();
                successMsg.append(e.getMessage());
                return successMsg.toString();
            }
            catch (Exception e) {
                e.printStackTrace();
                successMsg.append("文件操作失败！");
                return successMsg.toString();
            }
        }
        String zipFileName = pggName + "_" + ph + ".zip";
        try {
            packUtil.zipFolder(sourceFolderPath, sourceFolderPath+".zip");
            //将临时文件删除
//                Files.delete(Paths.get(zipFilePath.substring(0,zipFilePath.lastIndexOf('.'))));
//                Files.deleteIfExists(Paths.get(new File(sourceFolderPath).getAbsolutePath()));
            File folder = new File(sourceFolderPath);
            packUtil.deleteFolder(folder);
            System.out.println("Folder zipped successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String zipFilePath = new File(sourceFolderPath+".zip").getAbsolutePath();
        if (ztId==-1L){
            //直接下载
            try {
                packUtil.fileDownload(response,zipFilePath,zipFileName);
                successMsg.append("下载成功！");
            } catch (Exception e) {
                e.printStackTrace();
                successMsg.append("下载失败！");
                return successMsg.toString();
            }
        }else {
            Double fileSize = null;
            try{
                fileSize = (double) Files.size(Paths.get(zipFilePath));
            }catch (IOException e){
                System.err.println("获取文件大小时出错：" + e.getMessage());
            }
            //下载到指定载体
            if (packUtil.moveFileToPath(zipFilePath,place)) {
            successMsg.append("下载成功！");
                //添加下载记录
                yqXzjl = new YqXzjl();
                yqXzjl.setZtId(ztId);
                yqXzjl.setPggId(yqZpjl.getPggId());
                yqXzjl.setPggName(pggName);
                yqXzjl.setPh(ph);
                yqXzjl.setZpgzId(yqZpjl.getZpgzId());
                yqXzjl.setZpjlId(zpjlId);
                yqXzjl.setFilePath(place);
                yqXzjl.setFileName(zipFileName);
                yqXzjl.setFileSize(String.valueOf(fileSize));
                LoginUser user = SecurityUtils.getLoginUser();

                if(user == null){
                    user = new LoginUser();
                    user.setUserId(1L);
                }

                yqXzjl.setCreatorId(user.getUserId());
                yqXzjl.setCreateTime(DateUtils.getNowDate());
                yqZpjlMapper.insertYqXzjl(yqXzjl);
            }else {
                successMsg.append("下载失败！");
            }
        }
        //把载体ID存入组盘记录
        yqZpjl.setZtId(ztId);
        yqZpjlMapper.updateYqZpjl(yqZpjl);
        return successMsg.toString();
    }

    /**
     * 批量删除组盘记录及组盘明细
     *
     * @param pggId 需要删除的盘规格主键
     * @return 结果
     */
    @Override
    public String deleteYqZpjlByZpjlIds(HttpServletRequest request, Long pggId)
    {
        HttpSession session = request.getSession();
        List<Map<YqZpjl,List<YqZpmx>>> zpjlList = new LinkedList<>();
        StringBuilder successMsg = new StringBuilder();

        if (session.getAttribute("plan") != null ){
            zpjlList = (List<Map<YqZpjl,List<YqZpmx>>>) session.getAttribute("plan");
        }else {
            YqZpgz yqZpgz = selectYqZpgzByPggId(pggId);
            zpjlList = plan(request,yqZpgz);
        }

        Long[] zpjlIds = new Long[zpjlList.size()];
        if (session.getAttribute("zpjlIds") != null ){
            zpjlIds = (Long[]) session.getAttribute("zpjlIds");
        }else {
            int index = 0;
            for (Map<YqZpjl, List<YqZpmx>> map : zpjlList) {
                for (Map.Entry<YqZpjl, List<YqZpmx>> entry : map.entrySet()) {
                    YqZpjl yqZpjl = entry.getKey();
                    zpjlIds[index] = yqZpjl.getZpjlId();
                    index++;
                }
            }
        }

        int sumNum = 0;
        int successNum = 0;
        int failNum = 0;
        sumNum = zpjlIds.length;
        YqZpjl yqZpjl = new YqZpjl();
        YqZpmx yqZpmx = new YqZpmx();
        successNum = yqZpjlMapper.deleteYqZpjlByZpjlIds(yqZpjl.getTableName(),yqZpmx.getTableName(),zpjlIds);
        failNum = sumNum-successNum;
        return "删除成功！";
//        if (failNum>=0){
//            return "删除成功！";
//        }else {
//            return "删除失败！";
//        }
    }

    /**
     * 完成组盘
     *
     * @param zpjlIds 组盘记录主键
     * @return 结果
     */
    @Override
    public String complete(Long[] zpjlIds) {
        String sussessMsg = "";
//        String quantity = String.valueOf(zpjlIds.length);
        Integer quantity = zpjlIds.length;
        YqZpjl yqZpjl = new YqZpjl();
        yqZpjl.setZpjlId(zpjlIds[0]);
        if (null!=yqZpjlMapper.selectYqZpjlByZpjlId(yqZpjl)){
            yqZpjl = yqZpjlMapper.selectYqZpjlByZpjlId(yqZpjl);
            if (null!=yqZpjl.getPggId()){
                int successNum = 0;
                YqPgg yqPgg = new YqPgg();
                yqPgg.setPggId(yqZpjl.getPggId());
                yqPgg.setQuantity(quantity);
                //数量增加
                successNum = yqPggMapper.updateYqPggComplete(yqPgg);
                if (successNum==0){
                    sussessMsg = "组盘失败！";
                }else {
                    //将组盘记录下所有的档案的是否已组盘改为1
                    YqZpmx yqZpmx = new YqZpmx();
                    yqZpmx.setZpjlId(zpjlIds[0]);
                    if (null!=yqZpmxMapper.selectYqZpmxByZpjlId(yqZpmx)){
                        yqZpmx = yqZpmxMapper.selectYqZpmxByZpjlId(yqZpmx);
                        String userCode = SecurityUtils.getTenantCode();
                        String categoryTable = userCode + "_CATEGORY";
                        String DA_TABLE = "";
                        List<Map<String,String>> categoryMap=yqZpgzMapper.selectCategory(categoryTable,yqZpmx.getCategoryId());
                        //根据整理方式选择分表
                        if (!String.valueOf(categoryMap.get(0).get("TYPE")).equals("0")){
                            DA_TABLE = categoryMap.get(0).get("FOLDER_TABLE_NAME");
                        }else {
                            DA_TABLE = categoryMap.get(0).get("FILE_TABLE_NAME");
                        }
                        successNum = yqZpjlMapper.updateYqZpjlComplete(yqZpjl.getTableName(),yqZpmx.getTableName(),DA_TABLE,zpjlIds,yqZpjl.getPggId());
                        if (successNum == 0){
                            sussessMsg = "组盘失败！";
                        }else {
                            sussessMsg = "组盘成功！";
                        }
                    }else {
                        sussessMsg = "组盘失败！";
                    }
                }
            }else {
                sussessMsg = "组盘失败！";
            }
        }else {
            sussessMsg = "组盘失败！";
        }
        return sussessMsg;
    }

    //容量格式转换
    public static String convertToReadableSize(Double size) {
        if (size < 0) return "";

        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            Double fgb = ((Double) size / gb);
            return String.format("%.2f GB", fgb);
        } else if (size >= mb && size < gb) {
            Double fmb = ((Double) size / mb);
            return String.format("%.2f MB", fmb);
        } else if (size > kb && size < mb) {
            Double fkb = ((Double) size / kb);
            return String.format("%.2f KB", fkb);
        } else {
            return String.valueOf(size) + " bytes";
        }
    }

}
